'use strict'
import React, { Component} from 'react';
import {
    View,
    StyleSheet,
    Platform
} from 'react-native';
import RootSiblings from 'react-native-root-siblings'
import MessageBoxContainer from './MessageBoxContainer';

let sibling = undefined
let touchStartEvent=function(event){
    event.preventDefault();
}

class MessageBox extends Component {

    static displayName = 'MessageBox';
    static propTypes = MessageBoxContainer.propTypes;

    static show = (options) => {
        if(Platform.OS=='web'){
            document.addEventListener('touchmove',touchStartEvent,{passive:false})
        };
        sibling = new RootSiblings(
            <MessageBoxContainer
                {...options}
                visible={true}
                destroy={()=>{MessageBox.hide()}}
            />
        );
        return sibling;
    };

    static hide = () => {
        if(Platform.OS=='web'){
            document.removeEventListener('touchmove',touchStartEvent,{passive:false})
        };
        if (sibling instanceof RootSiblings) {
             sibling.destroy();
        } else {
            console.warn(`MessageBox.hide expected a \`RootSiblings\` instance as argument.\nBut got \`${typeof sibling}\` instead.`);
        }
    };

    _messagebox = null;

    constructor(props) {
        super(props);
        this.state = {
            visible: this.props.visible,
        };
        this.updataFlag = true;
    };

    _show = ()=>{
        this.container._open()
    }

    _close = ()=>{
        this.container._close()
    }

    componentDidMount = () => {
        this._messagebox = new RootSiblings(
            <MessageBoxContainer ref={(obj) =>{this.container = obj}}
                                 {...this.props}
                                 visible={this.state.visible}
            />
        );
    };

    componentDidUpdate(){
        this._messagebox.update(
            <MessageBoxContainer ref={(obj) =>{this.container = obj}}
                                    {...this.props}
                                    visible={this.state.visible}
            />
        );
    }

    componentWillUnmount = () => {
        this._messagebox.destroy();
    };

    render(){
        return null;
    }

}

const styles = StyleSheet.create({
        maskStyle: {
            position: 'absolute',
            backgroundColor: 'rgba(0, 0, 0, 0.6)',
            top: 0,
            bottom: 0,
            left: 0,
            right: 0,
            zIndex: 1,
            alignItems: 'center',
            justifyContent: 'center'
        },
    }
)

export {
    RootSiblings as Manager
};

export default MessageBox;